#!/bin/bash
# Author: liaojunhua
# QQ: 563293401
# ansible ssh host

# Source function library.
. /etc/init.d/functions

ListTags=$1
Hostini="/etc/ansible/inventory/default-hosts.ini"
Key="/etc/ansible/keys/{{ kaifa_user }}_id_rsa"
Port=$(grep -w $ListTags $Hostini |grep "ansible_port" |awk '{print $4}' |awk -F'=' '{print $2}')
IP=$(grep -w $ListTags $Hostini |grep "ansible_port" |awk '{print $2}' |awk -F'=' '{print $2}')
User=$(grep -w $ListTags $Hostini |grep "ansible_port" |awk '{print $5}' |awk -F'=' '{print $2}')
HostList=$(ansible all --list-hosts)

service_usage () {
    echo $"Usage: $0 Host"
    echo "...................................................."
    echo "Host List"
    echo "$HostList"
    exit 2
}

service_check () {
    if [[ $# -eq 0 ]]; then
        service_usage
    else
        grep -w $ListTags <<< $HostList >/dev/null 2>&1
        if [[ $? == 1 ]]; then
            service_usage
        fi
    fi
}

ssh_host () {
    ssh -i $Key -p $Port $User@$IP
}

case "$1" in
    $1 )
        [ $# -ne 1 ] && { service_usage; exit; }
        service_check
        ssh_host
        ;;

    * )
        service_usage
        ;;
esac
exit 0